package com.yuan.yblog.security.handler;

import com.alibaba.fastjson2.JSON;
import com.yuan.yblog.common.api.CommonResult;
import com.yuan.yblog.common.consts.RedisKey;
import com.yuan.yblog.common.service.EntityCacheService;
import com.yuan.yblog.common.utils.ServletUtils;
import com.yuan.yblog.security.util.JwtTokenUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;


import java.io.IOException;

/**
 * 自定义退出处理类
 */
@Configuration
@Slf4j
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler {

    @Autowired
    JwtTokenUtil jwtTokenUtil;
    @Autowired
    EntityCacheService entityCacheService;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        // 删除登录缓存
        String token = jwtTokenUtil.getToken(request);
        String userEmail = String.valueOf(jwtTokenUtil.getUserIdentityByToken(token));
        log.info("用户" + userEmail + "退出登陆");
        // 删除用户登录缓存
        entityCacheService.deleteEntity(RedisKey.AUTH_LOGIN_USER,userEmail);
        // 返回结果
        ServletUtils.renderString(response, JSON.toJSONString(CommonResult.success(null,"登出成功")));
    }
}
